/*
 *  SSCommentPanelController.m
 *  MESLib
 * 
 * Copyright 2003-2009 Starline Software Ltd
 * 
 * This file is part of MESLib.
 * 
 * MESLib is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * MESLib is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with MESLib. If not, see <http://www.gnu.org/licenses/>.
 */
//  Created by Tobias Haughton on Tue Jul 01 2003.
//

#import "SSCommentPanelController.h"
#import "SSCatalystDocument.h"

@implementation SSCommentPanelController

+ (id)sharedCommentPanelController {
   static SSCommentPanelController *sharedCommentPanelController = nil;

   if(!sharedCommentPanelController) {
      sharedCommentPanelController = [[SSCommentPanelController allocWithZone:[self zone]] init];
   }
   return sharedCommentPanelController;
}

- (id)init {

   if(floor(NSAppKitVersionNumber) >= 743) {
      isUsing103OrLater = YES;
      self = [super initWithWindowNibName:@"CommentPanel"];
   } else {
      //in 10.2
      isUsing103OrLater = NO;
      self = [super initWithWindowNibName:@"CommentPanelPre103"];
   }
   
   if (self) {
      [self setWindowFrameAutosaveName:@"CommentPanel"];
      [[NSNotificationCenter defaultCenter] addObserver:self
             selector:@selector(setNeedsUpdate)
                 name:@"SSCommentDataChanged"
               object:nil];
      [[NSNotificationCenter defaultCenter] addObserver:self
                                               selector:@selector(updateTableDisplay:)
                                                   name:@"SSCommentTableDisplayChanged"
                                                 object:nil];
      unusedTableColumns = [[NSMutableArray alloc] init];
   }
   return self;
}

- (void)awakeFromNib
{
   [self setupTable];
}

- (void)setMainWindow:(NSWindow *)mainWindow {
   needsUpdate = YES;
}

- (void)setupTable
{
   NSPopUpButtonCell *buttonCell = [[[NSPopUpButtonCell alloc] initTextCell:NSLocalizedString(@"Alert", nil) pullsDown:NO] autorelease];
   [[buttonCell itemAtIndex:0] setTag:SSCommentAlertType];
   [[buttonCell itemAtIndex:0] setImage:[NSImage imageNamed: @"alertMenuImage.jpg"]];
   [buttonCell setControlSize:NSSmallControlSize];

   [buttonCell insertItemWithTitle:NSLocalizedString(@"Note", nil) atIndex:[buttonCell numberOfItems]];
   [[buttonCell itemAtIndex:1] setTag:SSCommentNoteType];
   [[buttonCell itemAtIndex:1] setImage:[NSImage imageNamed: @"noteMenuImage.jpg"]];
   [buttonCell insertItemWithTitle:NSLocalizedString(@"Question", nil) atIndex:[buttonCell numberOfItems]];
   [[buttonCell itemAtIndex:2] setTag:SSCommentQuestionType];
   [[buttonCell itemAtIndex:2] setImage:[NSImage imageNamed: @"questionMenuImage.jpg"]];

   [[tableView tableColumnWithIdentifier:@"type"] setDataCell:buttonCell];
   
   [[[tableView tableColumnWithIdentifier:@"commentString"] dataCell] setWraps:YES];
   
   [tableView sizeLastColumnToFit];
   
   [tableView setDrawsGrid:NO];
   [tableView setDrawsGrid:YES];

   //enumerate through the table columns and remove the ones that shouldn't be displayed
   NSEnumerator *enumerator = [[tableView tableColumns] objectEnumerator];
   id column;
   NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
   NSString *keyString;

   while (column = [enumerator nextObject]) {
      [[column dataCell] setFont:[NSFont fontWithName:@"Helvetica" size:10]];
      
      keyString = [NSString stringWithFormat:@"SSCommentTable%@ColumnKey", [[column identifier] capitalizedString]]; //create a string for this columns preferences
      if(![defaults boolForKey:keyString]) {
         //the user wants to remove this column from the table
         [unusedTableColumns addObject:column];
         [tableView removeTableColumn:column];
      }
   }

   [tableView sizeLastColumnToFit];
   [tableView setAutosaveName:@"CommentTable"];
   [tableView setAutosaveTableColumns:YES];
}

- (void)updateTableDisplay:(NSNotification *)notification
{
   NSString *identifier;
   NSTableColumn *column;

   //get the identifier string
   switch([[notification object] tag]) {
      case preferenceCTDisplayCommentColumnTag:identifier = @"commentString";
         break;
      case preferenceCTDisplayXPositionColumnTag:identifier = @"xPosition";
         break;
      case preferenceCTDisplayYPositionColumnTag:identifier = @"yPosition";
         break;
      case preferenceCTDisplayTypeColumnTag:identifier = @"type";
         break;
      default:
         break;
   }

   //add or remove the tabel column
   if([[notification object] state]) {
      //we are adding the column
      column = [self unusedTableColumnWithIdentifier:identifier];
      if(column) {
         [tableView addTableColumn:column];
         [unusedTableColumns removeObjectIdenticalTo:column];
      }
   } else {
      //we are removing the collumn
      column = [tableView tableColumnWithIdentifier:identifier];
      if(column) {
         [unusedTableColumns addObject:column];
         [tableView removeTableColumn:column];
      }
   }

   [tableView sizeLastColumnToFit];
}

- (NSTableColumn *)unusedTableColumnWithIdentifier:(NSString *)string
{
   NSEnumerator *enumerator = [unusedTableColumns objectEnumerator];
   id anObject;

   while (anObject = [enumerator nextObject]) {
      if([[anObject identifier] isEqualToString:string]) {
         //we are holding the column
         return anObject;
      }
   }

   return nil;
}

- (void)setNeedsUpdate
{
   needsUpdate = YES;
}


- (void)windowDidUpdate:(NSNotification *)notification {
   //this is called each time the window updates, if something has changed
   //needsUpdate is set to YES elsewhere so we test it here and update as needed
   if(needsUpdate) {
      [self updateDataArray];
      needsUpdate = NO;
   }
}

- (IBAction)performSearch:(id)sender
{
   [self updateDataArray];
}

- (void)updateDataArray
{
   [dataArray release];
   
   if(isUsing103OrLater && ![[searchField stringValue] isEqualToString:[NSString string]]) {
      //user is searching
      dataArray = [[[[NSDocumentController sharedDocumentController] currentDocument] allCommentsContainingString:[searchField stringValue]] retain];     
   } else {
      dataArray = [[NSMutableArray arrayWithArray:[[[NSDocumentController sharedDocumentController] currentDocument] commentArray]] retain];
   }
   
   [tableView reloadData];
}

- (void)tableViewSelectionDidChange:(NSNotification *)note
{
   //get the view to scroll to this object
   int rowIndex = [tableView selectedRow];
   if(rowIndex != -1) {
      SSCatalystComment *comment = [dataArray objectAtIndex:rowIndex];
      [[[NSDocumentController sharedDocumentController] currentDocument] selectAndDisplayObject:[comment commentView]];
   }
}

//***********************************table view data source
- (int)numberOfRowsInTableView:(NSTableView *)aTableView
{
   return [dataArray count];
}

- (id)tableView:(NSTableView *)aTableView
objectValueForTableColumn:(NSTableColumn *)aTableColumn
            row:(int)rowIndex
{
   NSString *identifier = [aTableColumn identifier];
   id record = [dataArray objectAtIndex:rowIndex];
   return [record valueForKey:identifier];
}

- (void)tableView:(NSTableView *)aTableView
   setObjectValue:(id)anObject
   forTableColumn:(NSTableColumn *)aTableColumn
              row:(int)rowIndex
{
   NSString *identifier = [aTableColumn identifier];
   id record = [dataArray objectAtIndex:rowIndex];

   [record takeValue:anObject forKey:identifier];

   if([identifier isEqualToString:@"xPosition"] || [identifier isEqualToString:@"yPosition"]) {
      //redisplay the main chart so that the comments new position will be displayed
      [[[NSDocumentController sharedDocumentController] currentDocument] redisplay];
   }
}

- (NSTableView *)tableView
{
   return tableView;
}

- (NSMutableArray *)dataArray
{
   return dataArray;
}

- (void)dealloc
{
   [[NSNotificationCenter defaultCenter] removeObserver:self];
   [unusedTableColumns release];
   [dataArray release];
   [super dealloc];
}

@end
